package com.stxx.stiot2.auth2.topiam;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.stxx.stiot2.service.SysConfigService;
import com.xkcoding.http.support.HttpHeader;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthDefaultRequest;
import me.zhyd.oauth.utils.HttpUtils;
import me.zhyd.oauth.utils.UrlBuilder;
import org.noear.solon.Solon;


/**
 * TopIAM 认证请求
 *
 * @author xlsea
 * @since 2024-01-06
 */
@Slf4j
public class AuthTopIamRequest extends AuthDefaultRequest {



    /**
     * 设定归属域
     */
    public AuthTopIamRequest(AuthConfig config) {
        super(config, getAuthSource());
    }

    public AuthTopIamRequest(AuthConfig config, AuthStateCache authStateCache) {
        super(config,  getAuthSource(), authStateCache);
    }

    @Override
    public AuthToken getAccessToken(AuthCallback authCallback) {
        String body = doPostAuthorizationCode(authCallback.getCode());
        JSONObject jsonObject = JSONObject.parseObject(body);
        checkResponse(jsonObject);
        return AuthToken.builder()
                .accessToken(jsonObject.getString("access_token"))
                .refreshToken(jsonObject.getString("refresh_token"))
                .idToken(jsonObject.getString("id_token"))
                .tokenType(jsonObject.getString("token_type"))
                .scope(jsonObject.getString("scope"))
                .build();
    }

    @Override
    public AuthUser getUserInfo(AuthToken authToken) {
        String body = doGetUserInfo(authToken);
        JSONObject jsonObject = JSONObject.parseObject(body);
        checkResponse(jsonObject);
        AuthUser user = AuthUser.builder()
                .uuid(jsonObject.getString("sub"))
                .username(jsonObject.getString("preferred_username"))
                .nickname(jsonObject.getString("nickname"))
                .avatar(jsonObject.getString("picture"))
                .email(jsonObject.getString("email"))
                .token(authToken)
                .source(source.toString())
                .rawUserInfo(jsonObject)
                .build();
        return user;
    }

    @Override
    protected String doPostAuthorizationCode(String code) {
        HttpRequest request = HttpRequest.post(source.accessToken())
                .header("Authorization", "Basic " + Base64.encode(config.getClientId()+":"+config.getClientSecret()))
                .form("grant_type", "authorization_code")
                .form("code", code)
                .form("redirect_uri", config.getRedirectUri());
        HttpResponse response = request.execute();
        return response.body();
    }

    @Override
    protected String doGetUserInfo(AuthToken authToken) {
        return new HttpUtils(config.getHttpConfig()).get(source.userInfo(), null, new HttpHeader()
                .add("Content-Type", "application/json")
                .add("Authorization", "Bearer " + authToken.getAccessToken()), false).getBody();
    }


    @Override
    public String authorize(String state) {
        return UrlBuilder.fromBaseUrl(super.authorize(state))
                .queryParam("scope", StrUtil.join("%20", config.getScopes()))
                .build();
    }

    private static void checkResponse(JSONObject object) {
        // oauth/token 验证异常
        if (object.containsKey("error")) {
            throw new AuthException(object.getString("error_description"));
        }
        // user 验证异常
        if (object.containsKey("message")) {
            throw new AuthException(object.getString("message"));
        }
    }



    private static AuthSource getAuthSource(){

        SysConfigService configService = Solon.context().getBean(SysConfigService.class);
        JSONObject jsonObject = new JSONObject(configService.getConfig(SysConfigService.Keys.auth_topiam));
        String url = jsonObject.getString("server_url");
        AuthSource authSource = new AuthSource(){
            @Override
            public String authorize() {
                return url + "/oauth2/auth";
            }

            @Override
            public String accessToken() {
                return url + "/oauth2/token";
            }

            @Override
            public String userInfo() {
                return url + "/oauth2/userinfo";
            }

            @Override
            public Class<? extends AuthDefaultRequest> getTargetClass() {
                return AuthTopIamRequest.class;
            }

            @Override
            public String toString(){
                return "topiam";
            }
        };
        return authSource;
    }
}